package com.netty.demo.server.netty.udp;


import com.netty.demo.server.dto.UdpRequestMessage;
import com.netty.demo.server.netty.listener.ForwardMessageListener.ForwardMessage;
import com.netty.demo.server.netty.protocol.RequestProtocol;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * netty服务通道数据处理器
 *
 * @author yxl 余秀良
 * @version 1.0
 * <p>date: 2019年09月07日  下午10:52 </p>
 * <p>address: 四川成都 </p>
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class UdpServerChannelHandler extends SimpleChannelInboundHandler<RequestProtocol> {
    @Resource
    private ApplicationEventPublisher publisher;
    /**
     * 捕获异常
     *
     * @param ctx   ChannelHandlerContext
     * @param cause Throwable
     * @throws Exception Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("UdpServerChannelHandler 发生异常" + cause.getMessage());
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RequestProtocol msg) throws Exception {
        //TODO 解析数据内容进行处理
        //TODO 数据效验等等
        // TODO 发送响应给客户端

        publisher.publishEvent(new UdpRequestMessage(msg.getProtocolHeader(), msg.getData(), ctx));
        publisher.publishEvent(new ForwardMessage(ctx, msg.getRecipient()));
        //发送响应给客户端
        ByteBuf byteBuf = Unpooled.copiedBuffer("数据已收到", CharsetUtil.UTF_8);
        DatagramPacket datagramPacket = new DatagramPacket(byteBuf, msg.getSourceAddress());
        ctx.channel().writeAndFlush(datagramPacket);
    }
}
